package com.yun2.bms.service.impl;

import com.yun2.bms.constant.SystemConstant;
import com.yun2.bms.dao.IBookDao;
import com.yun2.bms.dao.ILendDao;
import com.yun2.bms.dao.IUserDao;
import com.yun2.bms.dao.impl.BookDaoImpl;
import com.yun2.bms.dao.impl.LendDaoImpl;
import com.yun2.bms.dao.impl.UserDaoImpl;
import com.yun2.bms.model.Lend;
import com.yun2.bms.model.User;
import com.yun2.bms.service.ILendService;
import com.yun2.bms.utils.DateUtils;

import java.util.Date;
import java.util.List;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/6/15
 */

public class LendServiceImpl implements ILendService {

    private ILendDao lendDao = new LendDaoImpl();

    private IUserDao userDao = new UserDaoImpl();

    private IBookDao bookDao = new BookDaoImpl();

    @Override
    public Integer getLendedNumberByUserId(int userId) {
        return this.lendDao.getLendedNumberByUserId(userId);
    }

    @Override
    public Integer getLendedNumberByBookId(int bookId) {
        return this.lendDao.getLendedNumberByBookId(bookId);
    }

    @Override
    public int add(int userId, int bookId) {
        return this.lendDao.add(userId, bookId);
    }

    @Override
    public boolean bookIsLendedByUserId(int bookId, int userId) {
        return this.lendDao.bookIsLendedByUserId(bookId, userId);
    }

    @Override
    public List<Lend> getAllByUserId(int userId) {
        User user = this.userDao.get(userId);
        List<Lend> list = this.lendDao.getAllByUserId(userId);
        //添加用户名，图书名称，预计归还日期，超期天数
        if(list != null){
            for (Lend lend : list){
                lend.setUserName(user.getUserName());
                lend.setBookName(this.bookDao.get(lend.getBookId()).getBookName());
                //判断用户的角色信息
                String role = user.getRole();
                Date lendDate = (Date) lend.getLendDate();
                //根据角色信息确定还书日期和超期天数（分为学生和非学生）
                if(role.equals(SystemConstant.Role.ROLE_STUDENT)){
                    lend.setReturnDate(DateUtils.addDays(lendDate, SystemConstant.MAX_LEND_DAYS_OF_STUDENT));
                    lend.setExpireDays(DateUtils.differentDaysByMillisecond(lendDate, new Date()) - SystemConstant.MAX_LEND_DAYS_OF_STUDENT);
                }else{
                    lend.setReturnDate(DateUtils.addDays(lendDate, SystemConstant.MAX_LEND_DAYS_OF_TEACHER));
                    lend.setExpireDays(DateUtils.differentDaysByMillisecond(lendDate, new Date()) - SystemConstant.MAX_LEND_DAYS_OF_TEACHER);
                }
            }
        }
        return list;
    }
}
